import messaging
import inbox
import appuifw
import e32
import time
try:
	import msgquery # Non-native module
except:
	import globalui
	msgqueryloaded = False
else:
	msgqueryloaded = True
try:
	import msys # Non-native module
except:
	msysloaded = False
else:
	msysloaded = True

__title__ = "SMStoFlash"
__version__ = "0.3"
__shell__ = 1

class _SMStoFlash:
	def __init__(self):
		self.msgqueryloaded = msgqueryloaded
		self.msysloaded = msysloaded
		self.lock = e32.Ao_lock()
		appuifw.app.title = unicode("%s %s" % (__title__, __version__))
		appuifw.app.exit_key_handler = self.exit_key_handler
		appuifw.app.menu = [(u"Simulate", self.simulate), (u"Stop & Exit", lambda: self.exit_key_handler(exit = True))]
		self.inbox = inbox.Inbox()

	def _setup_app(self):
		appuifw.app.screen = "normal"
		self.text = appuifw.Text()
		self.text.font = u"Nokia Sans S60", 13
		self.text.color = 0x321FED
		self.text.style = appuifw.STYLE_BOLD
		self.text.set(u"Welcome to %s %s" % (__title__, __version__))
		if self.msysloaded:
			self.old_exit_text = msys.exit_text(u"Hide")
			appuifw.app.menu.insert(0,(u"Go to BackGround", self.exit_key_handler))
		appuifw.app.body = self.text

	def exit_key_handler(self, exit = False):
		if self.msysloaded and not exit:
			msys.set_hidden(True)
			msys.set_system(True)
			msys.send_bg()
			return
		exit = True
		if exit:
			if self.msysloaded:
				msys.exit_text(self.old_exit_text)
			self.lock.signal()
			if not __shell__:
				sys.exit()

	def _get_sender(self, id):
		try:
			e32.ao_sleep(0.1)
			self._sms_time = self.inbox.time(id)
			self._from = self.inbox.address(id)
			self._messagge = self.inbox.content(id)
			self.show_flash(self._messagge, self._from)
		except Exception, err:
			error_time = time.strftime('%d/%m/%Y %H:%M:%S', time.localtime())
			self.text.set(unicode("%s: %s" % (error_time, err)))

	def show_flash(self, message, sender):
		if self.msgqueryloaded:
			msgquery.infopopup(message, sender, msgquery.RClose)
		else:
			globalui.global_msg_query(message, sender)
		self.text.set(u"Last SMS at %s" % (time.strftime('%d/%m/%Y %H:%M:%S', time.localtime(self._sms_time))))
		self.inbox.set_unread(self.inbox.sms_messages()[0], 0)

			
	def simulate(self):
		self.text.set(u"Simulating ...")
		mess = self.inbox.sms_messages()
		if len(mess) > 0:
			self.inbox.set_unread(mess[0], 1)
			self._get_sender(mess[0])

	def run(self):
		self._setup_app()
		self.inbox.bind(self._get_sender)
		self.lock.wait()
	
application = _SMStoFlash()
application.run()